package com.tinem.platform.web.netty.websocket.util;

import com.tinem.platform.module.pojo.enums.message.Message;
import com.tinem.platform.web.netty.NettyWebApplication;
import com.tinem.platform.web.netty.websocket.message.Command;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.UUID;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className MessageUtil
 * @description
 * @site
 * @company
 * @create 2021/11/30 19:36:58
 */
public class MessageUtil {

    /**
     * 发送消息
     * @param ctx
     */
    public static void sendMessage(ChannelHandlerContext ctx, Message message,boolean success,String msg){
        message.setRet_time(System.currentTimeMillis());
        message.setSuccess(success);
        message.setMessage(msg);
        TextWebSocketFrame tws = new TextWebSocketFrame(
                message.toString()
        );
        // 返回【谁发的发给谁】
        ctx.channel().writeAndFlush(tws);
    }
    public static void sendMessage(ChannelHandlerContext ctx, Message message){
        sendMessage(ctx,message,true,"success");
    }


    public static void call(ChannelHandlerContext ctx, Message message){
        Command command = NettyWebApplication.applicationContext.getBean("command_"+message.getCommand().name(), Command.class);
        message.setAccept_time(System.currentTimeMillis());
        message.setServer_msg_id(UUID.randomUUID().toString());
        message.setSession_id(ctx.channel().id().asLongText());
        command.call(ctx,message);
    }
}
